extends Node2D

var damage = 20
var radius = 100.0
var source = null
var duration = 0.6  # 沙爆效果持续时间
var time_alive = 0.0
var max_scale = 1.0  # 最大缩放比例
var has_damaged_player = false

func _ready():
	# 设置初始缩放
	scale = Vector2(0.1, 0.1)
	
	# 播放音效（如果有）
	if has_node("AudioStreamPlayer2D"):
		$AudioStreamPlayer2D.play()

func _process(delta):
	# 更新生命周期
	time_alive += delta
	
	# 计算当前缩放比例
	var current_scale_factor = 0.0
	
	if time_alive < duration * 0.3:
		# 前30%时间快速增大
		current_scale_factor = time_alive / (duration * 0.3) * max_scale
	else:
		# 后70%时间缓慢减小
		current_scale_factor = (1.0 - (time_alive - duration * 0.3) / (duration * 0.7)) * max_scale
	
	# 应用缩放
	scale = Vector2(current_scale_factor, current_scale_factor)
	
	# 更新透明度（逐渐消失）
	var alpha = 1.0 - (time_alive / duration)
	modulate.a = alpha
	
	# 检测玩家是否在沙爆范围内（只在爆发时检测一次）
	if not has_damaged_player and time_alive >= duration * 0.3 and time_alive <= duration * 0.4:
		var player = get_tree().get_first_node_in_group("player")
		if player and is_instance_valid(player):
			var distance = global_position.distance_to(player.global_position)
			var effect_radius = radius * current_scale_factor / max_scale
			
			if distance <= effect_radius:
				# 对玩家造成伤害
				player.take_damage(damage)
				
				# 击退效果
				var knockback_direction = (player.global_position - global_position).normalized()
				if player.has_method("apply_knockback"):
					player.apply_knockback(knockback_direction * 200)
				
				has_damaged_player = true
	
	# 到达最大存活时间后消失
	if time_alive >= duration:
		queue_free()
